//
//  JYLoginController.m
//  JYFarm
//
//  Created by 花花 on 2017/10/10.
//  Copyright © 2017年 花花. All rights reserved.
//

#import "JYLoginController.h"
#import "ChangeBuTitleTool.h"
#import "JYSetingPwdController.h"
#import "BaseTabBarViewController.h"
#import "JYRegisterController.h"
#import "AFNetworking.h"
#import "JYUserModel.h"
#import "UIView+HUD.h"

@interface JYLoginController (){

   UIButton * _smsCodeBtn;
    NSString *codeStr;
}
//账号
@property (weak, nonatomic) IBOutlet UITextField *accountTextField;
//密码或者验证码
@property (weak, nonatomic) IBOutlet UITextField *pwdTextField;

//获取验证码
@property (weak, nonatomic) IBOutlet UIButton *getCodeBtn;

//提示内容
@property (weak, nonatomic) IBOutlet UILabel *showLabel;

//登录按钮
@property (weak, nonatomic) IBOutlet UIButton *loginBtn;

@property (weak, nonatomic) IBOutlet UIImageView *imgView;

@property(assign, nonatomic)BOOL isPwdLogin;
@end

@implementation JYLoginController

#pragma mark - Life Cycle
- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.title = @"登录";
    self.view.backgroundColor = [UIColor whiteColor];
}
- (void)viewWillAppear:(BOOL)animated{

    [super viewWillAppear:animated];
    _isPwdLogin = NO;
}

#pragma mark - loadData sendCode
- (void)sendCodeFormNetwork{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"phone"] =  self.accountTextField.text;
    //操作类型(0登录1注册 2找回密
    param[@"operateType"]= @"0";
    
    [HTTPRequest POST:kGetSmsCodeUrl parameter:param success:^(id resposeObject) {
        
        NSLog(@"发送验证码……%@",resposeObject);
        
        if (SUCCESS) {
            codeStr = resposeObject[@"data"];
        }else{
            
            [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
    } failure:^(NSError *error) {
        
        [MBProgressHUD LY_ShowError:kNoNetworkTips time:2.0];
    }];
}

- (void)loginFormNetwork{
    
    NSMutableDictionary *param = [NSMutableDictionary dictionary];
    param[@"userName"] =  self.accountTextField.text;
    //    self.accountTextField.text;
    param[@"terminalType"]= @(2);
    
    if (_isPwdLogin) {
        param[@"password"]= [LYTools MD5ForLower32Bate:self.pwdTextField.text];
        //        [LYTools MD5ForLower32Bate:self.pwdTextField.text];
        //        @"e10adc3949ba59abbe56e057f20f883e";
    }else{
        param[@"smsCode"]= codeStr;
    }
    
    [HTTPRequest POST:kLoginUrl parameter:param success:^(id resposeObject) {
        
        NSLog(@"%@",resposeObject);
        
        if (SUCCESS) {
            
            LH.token = resposeObject[@"data"][@"token"];
            LH.userId =  resposeObject[@"data"][@"userId"];
            JYUserModel *model = [JYUserModel mj_objectWithKeyValues:resposeObject[@"data"]];
            //保存用户信息到本地
            [LH saveUserInfoToLocal:model];
            [LH loginSuccessDataHandle];
            //保存到内存中
            LH.userInfor = model;
            NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
            [userDefaults setObject: param[@"userName"] forKey:kAccount];
            [userDefaults setObject: param[@"password"] forKey:kPassword];
            //因为没有个人信息的界面 则不能在首页掉接口 获取店家名称 美点和商家名称得存本地
            [userDefaults setObject: model.freeCash forKey:kFreeCash];
            [userDefaults setObject: model.merchantName forKey:kMerchantName];
            [userDefaults synchronize];
            
            BaseTabBarViewController *tabBar = [[BaseTabBarViewController alloc]init];
            [self presentViewController:tabBar animated:YES completion:nil];
            
        }else if([resposeObject[@"result"] integerValue] == 1){
            
            [MBProgressHUD LY_ShowError:@"账号密码错误" time:2.0];
            
        }else{
            
            self.showLabel.text = resposeObject[@"msg"];
            //        [MBProgressHUD LY_ShowError:resposeObject[@"msg"] time:2.0];
        }
    } failure:^(NSError *error) {
        self.loginBtn.userInteractionEnabled = YES;
        [MBProgressHUD LY_ShowError:(kNoNetworkTips) time:2.0];
    }];
}
#pragma mark - SEL Methods
- (IBAction)getCodeOnClick:(UIButton *)sender {
    
    if (self.accountTextField.text.length == 0) {
        
        [MBProgressHUD LY_ShowError:@"请输入账号" time: 2.0];
        return;
    }
    [self sendCodeFormNetwork];
    __block int MaxTime =kGlobalGetVaildCodeTime;
    _smsCodeBtn = sender;
    dispatch_queue_t queue=dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t _timer=dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0, queue);
    dispatch_source_set_timer(_timer, dispatch_walltime(NULL, 0), 1.0*NSEC_PER_SEC, 0);
    dispatch_source_set_event_handler(_timer, ^{
        if (MaxTime<=0) {
            dispatch_source_cancel(_timer);
            //dispatch_release(_timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                //倒计时结束
                _smsCodeBtn =(UIButton*)[self.view viewWithTag:100];
                [_smsCodeBtn setTitle:@"重新获取" forState:UIControlStateNormal];
                [_smsCodeBtn setUserInteractionEnabled:YES];
                
                [_smsCodeBtn setTitleColor:kThemeColor forState:UIControlStateNormal];
                
            });
        }else{
            NSString* strTime=[NSString stringWithFormat:@"%d s ",(int)(MaxTime)];
            dispatch_async(dispatch_get_main_queue(), ^{
                //倒计时
                _smsCodeBtn=(UIButton*)[self.view viewWithTag:100];
                [_smsCodeBtn setTitle:strTime forState:UIControlStateNormal];
                
                //                _smsCodeBtn.backgroundColor =[UIColor colorWithHexString:@"b1b1b1"];
                [_smsCodeBtn setUserInteractionEnabled:NO];
            });
            MaxTime--;
        }
    });
    dispatch_resume(_timer);

}
//密码登录、短信验证码登录
- (IBAction)loginmanner:(UIButton *)sender {
    if ([sender.titleLabel.text isEqualToString:@"密码登录"]) {
        
        [ChangeBuTitleTool changeBuTitleWithText:^(NSString *titleText) { //短信验证码登录
            [sender setTitle:titleText forState:(UIControlStateNormal)];
            _getCodeBtn.hidden = YES;
            _isPwdLogin = YES;
            _pwdTextField.placeholder = @"请输入密码";
            _imgView.image = [UIImage imageNamed:@"login_verification_code_icon"];
            
            
        }];
    }else{
        
        [ChangeBuTitleTool changeBuTitleText:^(NSString *titleText) { //密码登录
            [sender setTitle:titleText forState:(UIControlStateNormal)];

            _isPwdLogin = NO;
            _getCodeBtn.hidden = NO;
            _pwdTextField.placeholder = @"请输入验证码";
            _imgView.image = [UIImage imageNamed:@"login_password"];
            
        }];
    }
}

//登录
- (IBAction)loginOnClick:(UIButton *)sender {
    
    if (self.accountTextField.text.length == 0) {
        
        [MBProgressHUD LY_ShowError:@"请输入账号" time: 2.0];
        return;
    }else if (self.pwdTextField.text.length == 0){
        
        [MBProgressHUD LY_ShowError:_isPwdLogin?@"请输入密码":@"请输入验证码" time: 2.0];
        return;
    }
    [self loginFormNetwork];
}
//新用户注册
- (IBAction)registerOnClick:(id)sender {
    
    [self.navigationController pushViewController:[JYRegisterController new] animated:YES];
}
//忘记密码
- (IBAction)forgetPwd:(id)sender {
    
    JYSetingPwdController *settingVc = [[JYSetingPwdController alloc]initWithIsSetingPwd:YES];
    [self.navigationController pushViewController:settingVc animated:YES];
}

@end
